package com.amap.service;

import java.util.ArrayList;
import java.util.Collections;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.amap.model.Location;
import com.amap.model.Place;
import com.amap.url.util.HttpRequestUtil;

public class GooglePlacesService {

	private static GooglePlacesService googleService = null;

	private GooglePlacesService(){};

	public static GooglePlacesService getInstace(){
		if(googleService == null)
			googleService = new GooglePlacesService();
		return googleService;
	}

	public ArrayList<Place> getLocation(String url) {

		ArrayList<Place> places = new ArrayList<Place>();

		String result = HttpRequestUtil.getFileContent(url);

		if (result == null){
			Log.e("NGVL", "Falha ao acessar WS");
			return null;
		}

		try {
			JSONObject json = new JSONObject(result);
			JSONArray array = (JSONArray) json.get("results");
			
			//Log.d("lng", array.length()+"");

			for (int i = 0; i < array.length(); i++) {

				Double lat =  array.getJSONObject(i)
						.getJSONObject("geometry").getJSONObject("location")
						.getDouble("lat");

				Double lng = array.getJSONObject(i)
						.getJSONObject("geometry").getJSONObject("location")
						.getDouble("lng");


				String  idGMaps = array.getJSONObject(i).getString("id");

				String name = array.getJSONObject(i).getString("name");

				String adress = array.getJSONObject(i).getString("vicinity");
				
				float rating;
				
				try {
					rating = Float.valueOf(array.getJSONObject(i).getString("rating"));
				} catch (JSONException je) {
					rating = 0;
				}
				
				places.add(new Place(new Location(lat, lng), idGMaps, name, adress, rating));

			}
			
			Collections.sort(places);

		} catch (JSONException e) {     
			Log.e("NGVL", "Erro no parsing do JSON", e);
		}

		return places;

	}


}
